function renderCart(listId, editable = true) {
    let cart = JSON.parse(localStorage.getItem('cart') || '[]');
    let html = '';
    let total = 0;
    cart.forEach(item => {
        const p = getProductById(item.id);
        if (!p) return;
        total += p.price * item.quantity;
        html += `
            <div class="cart-item">
                <img src="../${p.image}" alt="${p.name}" onerror="this.src='../images/icons/default.png'">
                <span>${p.name}</span>
                <span>￥${p.price}</span>
                <span>数量：${item.quantity}</span>
                ${editable ? `<button onclick="removeFromCart(${item.id})">删除</button>` : ''}
            </div>
        `;
    });
    html += `<div>总价：￥${total}</div>`;
    document.getElementById(listId).innerHTML = html;
}
function removeFromCart(id) {
    let cart = JSON.parse(localStorage.getItem('cart') || '[]');
    cart = cart.filter(item => item.id != id);
    localStorage.setItem('cart', JSON.stringify(cart));
    renderCart('cartList');
}
if (location.pathname.endsWith('cart.html')) {
    renderCart('cartList');
}
if (location.pathname.endsWith('checkout.html')) {
    renderCart('checkoutList', false);
    document.getElementById('orderForm').onsubmit = function(e) {
        e.preventDefault();
        localStorage.removeItem('cart');
        document.getElementById('orderMsg').textContent = '订单提交成功！';
    };
}

if (location.pathname.endsWith('checkout.html')) {
    renderCart('checkoutList', false);
    document.getElementById('orderForm').onsubmit = function(e) {
        e.preventDefault();
        const user = localStorage.getItem('currentUser');
        if (!user) {
            document.getElementById('orderMsg').textContent = '请先登录';
            return;
        }
        let cart = JSON.parse(localStorage.getItem('cart') || '[]');
        let products = cart.map(item => {
            const p = getProductById(item.id);
            return {name: p.name, quantity: item.quantity, price: p.price};
        });
        let total = products.reduce((sum, item) => sum + item.price * item.quantity, 0);
        // 保存订单
        let orders = JSON.parse(localStorage.getItem('orders_' + user) || '[]');
        orders.push({
            time: new Date().toLocaleString(),
            items: products,
            total: total
        });
        localStorage.setItem('orders_' + user, JSON.stringify(orders));
        localStorage.removeItem('cart');
        document.getElementById('orderMsg').textContent = '订单提交成功！';
    };
}